package com.ybkj.daijia.api.weixin.handler;

import com.ybkj.daijia.serverUtils.SettingUtils;
import com.ybkj.daijia.api.weixin.WxMsgType;
import com.ybkj.daijia.api.weixin.entity.WxBaseMsgEntity;
import com.ybkj.daijia.api.weixin.entity.WxBaseRespEntity;
import com.ybkj.daijia.api.weixin.entity.WxRespTextEntity;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

@Component
@Scope("singleton")
public class HandlerFactory {


    private static final Logger logger = LoggerFactory.getLogger(HandlerFactory.class);
    @Autowired(required = false)
    List<WxHandler> handlers;
    @Autowired
    private SettingUtils settingUtils;

    /**
     * 处理微信收到的消息
     *
     * @param msg
     * @return
     * @throws DocumentException
     */
    public Element handle(WxBaseMsgEntity msg) throws DocumentException {

        List<WxHandler> handlerList = new ArrayList<WxHandler>();
        handlerList.addAll(handlers);
        Collections.sort(handlerList, new WxMessageHandlerComparator());

        logger.info("handlers size: {}", handlerList.size());

        Map<String, Object> context = new HashMap<String, Object>();

        WxBaseRespEntity result = null;

        for (WxHandler handler : handlerList) {
            if (handler.canHandle(msg)) {
                result = handler.doHandle(msg, context, result);
                if (null != result) {
                    return result.toXML();
                }
                return null;
            }
        }

        //默认信息
        WxRespTextEntity text = new WxRespTextEntity();
        text.setContent(settingUtils.getWx().getWxUnsubscribe());
        text.setCreatedDate(new Date());
        text.setCreateTime(text.getCreatedDate().getTime());
        text.setFromUserName(msg.getToUserName());
        text.setToUserName(msg.getFromUserName());
        text.setFuncFlag(0);
        text.setMsgType(WxMsgType.text.name());

        return text.toXML();
    }


}

class WxMessageHandlerComparator implements Comparator<WxHandler> {

    /*
     * (non-Javadoc)
     *
     * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
     */
    public int compare(WxHandler o1, WxHandler o2) {
        if (o1.priority() > o2.priority()) {
            return -1;
        } else if (o1.priority() < o2.priority()) {
            return 1;
        } else {
            return 0;
        }
    }

}